package com.jiniutech.common.util.wx;

import com.jiniutech.common.util.wx.entity.message.BaseMessage;
import com.jiniutech.common.util.wx.entity.message.TextReceiveMessage;
import com.jiniutech.common.util.wx.entity.message.WxField;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.lang.reflect.Field;

public class MessageUtil {
    public static BaseMessage getMessage(String xmlStr) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(xmlStr);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);

            Element root = document.getDocumentElement();
            switch (root.getElementsByTagName("MsgType").item(0).getTextContent()) {
                case "text":
                    TextReceiveMessage message = (TextReceiveMessage) getBean(root, TextReceiveMessage.class);
                    return message;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object getBean(Element root, Class clazz) {
        Field[] fields = clazz.getFields();
        Object o = null;
        try {
            o = clazz.newInstance();
            for (Field field : fields) {
                field.setAccessible(true);
                WxField wxFieldAnnotation = field.getAnnotation(WxField.class);
                if (field.getType().equals(Long.class)) {
                    field.set(o, Long.valueOf(root.getElementsByTagName(wxFieldAnnotation.name()).item(0).getTextContent()));
                } else {
                    field.set(o, root.getElementsByTagName(wxFieldAnnotation.name()).item(0).getTextContent());
                }
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return o;
    }
}
